import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { WeatherRecord, FilterOptions, ChartData } from '@/types'
import { ElMessage } from 'element-plus'
import { useWeatherStore } from './weather'

export const useRecordsStore = defineStore('records', () => {
  // 状态
  const records = ref<WeatherRecord[]>([])
  const filters = ref<FilterOptions>({
    startDate: null,
    endDate: null,
    cities: [],
    conditions: [],
    temperatureRange: undefined
  })
  const selectedRecords = ref<Set<string>>(new Set())
  
  // 从localStorage加载记录
  const loadRecords = () => {
    try {
      const saved = localStorage.getItem('weather-records')
      if (saved) {
        records.value = JSON.parse(saved)
      }
    } catch (error) {
      console.error('加载记录失败:', error)
      ElMessage.error('加载历史记录失败')
    }
  }
  
  // 保存到localStorage
  const persistRecords = () => {
    try {
      localStorage.setItem('weather-records', JSON.stringify(records.value))
    } catch (error) {
      console.error('保存记录失败:', error)
    }
  }
  
  // 计算属性：过滤后的记录
  const filteredRecords = computed(() => {
    return records.value.filter(record => {
      // 日期过滤
      const recordDate = new Date(record.createdAt)
      if (filters.value.startDate && recordDate < filters.value.startDate) return false
      if (filters.value.endDate && recordDate > filters.value.endDate) return false
      
      // 城市过滤
      if (filters.value.cities?.length && !filters.value.cities.includes(record.city)) return false
      
      // 天气状况过滤
      if (filters.value.conditions?.length && !filters.value.conditions.includes(record.condition)) return false
      
      // 温度范围过滤
      if (filters.value.temperatureRange) {
        const { min, max } = filters.value.temperatureRange
        if (record.temperature < min || record.temperature > max) return false
      }
      
      return true
    })
  })
  
  // 计算属性：统计数据
  const statistics = computed(() => {
    const stats = {
      totalRecords: filteredRecords.value.length,
      averageTemperature: 0,
      averageHumidity: 0,
      cityCount: 0,
      conditionDistribution: new Map<string, number>(),
      cityFrequency: new Map<string, number>()
    }
    
    if (filteredRecords.value.length === 0) return stats
    
    let tempSum = 0
    let humiditySum = 0
    const cities = new Set<string>()
    
    filteredRecords.value.forEach(record => {
      tempSum += record.temperature
      humiditySum += record.humidity
      cities.add(record.city)
      
      // 天气状况分布
      const count = stats.conditionDistribution.get(record.condition) || 0
      stats.conditionDistribution.set(record.condition, count + 1)
      
      // 城市查询频率
      const cityCount = stats.cityFrequency.get(record.city) || 0
      stats.cityFrequency.set(record.city, cityCount + 1)
    })
    
    stats.averageTemperature = Math.round(tempSum / filteredRecords.value.length)
    stats.averageHumidity = Math.round(humiditySum / filteredRecords.value.length)
    stats.cityCount = cities.size
    
    return stats
  })
  
  // 计算属性：图表数据
  const chartData = computed((): ChartData => {
    const labels: string[] = []
    const temperatures: number[] = []
    const humidities: number[] = []
    
    // 取最近30条记录用于图表
    const recentRecords = filteredRecords.value.slice(0, 30).reverse()
    
    recentRecords.forEach(record => {
      const date = new Date(record.createdAt)
      labels.push(`${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`)
      temperatures.push(record.temperature)
      humidities.push(record.humidity)
    })
    
    return {
      labels,
      datasets: [
        {
          label: '温度 (°C)',
          data: temperatures,
          borderColor: '#409EFF',
          backgroundColor: 'rgba(64, 158, 255, 0.1)'
        },
        {
          label: '湿度 (%)',
          data: humidities,
          borderColor: '#67C23A',
          backgroundColor: 'rgba(103, 194, 58, 0.1)'
        }
      ]
    }
  })
  
  // 添加记录
  const addRecord = (weather: WeatherRecord | any) => {
    const weatherStore = useWeatherStore()
    
    // 如果传入的是Weather对象，转换为WeatherRecord
    const record: WeatherRecord = {
      ...weather,
      recordId: `record-${Date.now()}`,
      createdAt: new Date().toISOString(),
      isManual: false
    }
    
    // 限制最大记录数
    if (records.value.length >= 500) {
      records.value.pop()
    }
    
    records.value.unshift(record)
    persistRecords()
    
    ElMessage.success('天气记录已保存')
  }
  
  // 手动添加记录
  const addManualRecord = (data: Partial<WeatherRecord>) => {
    const record: WeatherRecord = {
      id: `manual-${Date.now()}`,
      recordId: `record-${Date.now()}`,
      city: data.city || '未知城市',
      temperature: data.temperature || 20,
      temperatureUnit: data.temperatureUnit || 'C',
      humidity: data.humidity || 50,
      windSpeed: data.windSpeed || 0,
      windDirection: data.windDirection || 'N',
      condition: data.condition || '未知',
      conditionCode: data.conditionCode || '000',
      icon: data.icon || '01d',
      description: data.description || '',
      pressure: data.pressure || 1013,
      visibility: data.visibility || 10000,
      sunrise: data.sunrise || '06:00',
      sunset: data.sunset || '18:00',
      timestamp: new Date().toISOString(),
      lastUpdated: new Date().toISOString(),
      createdAt: new Date().toISOString(),
      isManual: true,
      notes: data.notes
    }
    
    records.value.unshift(record)
    persistRecords()
    
    ElMessage.success('手动记录已添加')
  }
  
  // 更新记录
  const updateRecord = (id: string, data: Partial<WeatherRecord>) => {
    const index = records.value.findIndex(r => r.recordId === id)
    if (index !== -1) {
      records.value[index] = {
        ...records.value[index],
        ...data,
        updatedAt: new Date().toISOString()
      }
      persistRecords()
      ElMessage.success('记录已更新')
    }
  }
  
  // 删除记录
  const deleteRecord = (id: string) => {
    records.value = records.value.filter(r => r.recordId !== id)
    persistRecords()
    ElMessage.success('记录已删除')
  }
  
  // 批量删除
  const deleteSelectedRecords = () => {
    records.value = records.value.filter(r => !selectedRecords.value.has(r.recordId))
    selectedRecords.value.clear()
    persistRecords()
    ElMessage.success('批量删除成功')
  }
  
  // 清空所有记录
  const clearAllRecords = () => {
    records.value = []
    selectedRecords.value.clear()
    persistRecords()
    ElMessage.success('所有记录已清空')
  }
  
  // 导出记录
  const exportRecords = (format: 'json' | 'csv' = 'json') => {
    const dataToExport = selectedRecords.value.size > 0
      ? records.value.filter(r => selectedRecords.value.has(r.recordId))
      : filteredRecords.value
    
    if (dataToExport.length === 0) {
      ElMessage.warning('没有可导出的记录')
      return
    }
    
    let content: string
    let filename: string
    let mimeType: string
    
    if (format === 'json') {
      content = JSON.stringify(dataToExport, null, 2)
      filename = `weather-records-${Date.now()}.json`
      mimeType = 'application/json'
    } else {
      // CSV格式
      const headers = ['城市', '温度', '湿度', '风速', '天气', '记录时间']
      const rows = dataToExport.map(r => [
        r.city,
        `${r.temperature}°${r.temperatureUnit}`,
        `${r.humidity}%`,
        `${r.windSpeed}m/s`,
        r.condition,
        new Date(r.createdAt).toLocaleString()
      ])
      
      content = [headers, ...rows].map(row => row.join(',')).join('\n')
      filename = `weather-records-${Date.now()}.csv`
      mimeType = 'text/csv'
    }
    
    // 创建下载链接
    const blob = new Blob([content], { type: mimeType })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    link.click()
    URL.revokeObjectURL(url)
    
    ElMessage.success(`导出成功：${dataToExport.length}条记录`)
  }
  
  // 导入记录
  const importRecords = async (file: File) => {
    try {
      const text = await file.text()
      let importedRecords: WeatherRecord[]
      
      if (file.name.endsWith('.json')) {
        importedRecords = JSON.parse(text)
      } else {
        ElMessage.error('不支持的文件格式')
        return
      }
      
      // 验证数据格式
      if (!Array.isArray(importedRecords)) {
        ElMessage.error('文件格式错误')
        return
      }
      
      // 合并记录（避免重复）
      const existingIds = new Set(records.value.map(r => r.recordId))
      const newRecords = importedRecords.filter(r => !existingIds.has(r.recordId))
      
      records.value.unshift(...newRecords)
      persistRecords()
      
      ElMessage.success(`成功导入${newRecords.length}条记录`)
    } catch (error) {
      ElMessage.error('导入失败：' + (error as Error).message)
    }
  }
  
  // 更新过滤器
  const updateFilters = (newFilters: Partial<FilterOptions>) => {
    filters.value = { ...filters.value, ...newFilters }
  }
  
  // 重置过滤器
  const resetFilters = () => {
    filters.value = {
      startDate: null,
      endDate: null,
      cities: [],
      conditions: [],
      temperatureRange: undefined
    }
  }
  
  // 切换记录选择
  const toggleRecordSelection = (recordId: string) => {
    if (selectedRecords.value.has(recordId)) {
      selectedRecords.value.delete(recordId)
    } else {
      selectedRecords.value.add(recordId)
    }
  }
  
  // 全选/取消全选
  const toggleSelectAll = () => {
    if (selectedRecords.value.size === filteredRecords.value.length) {
      selectedRecords.value.clear()
    } else {
      filteredRecords.value.forEach(r => selectedRecords.value.add(r.recordId))
    }
  }
  
  // 初始化
  loadRecords()
  
  return {
    // 状态
    records,
    filters,
    selectedRecords,
    
    // 计算属性
    filteredRecords,
    statistics,
    chartData,
    
    // 方法
    addRecord,
    addManualRecord,
    updateRecord,
    deleteRecord,
    deleteSelectedRecords,
    clearAllRecords,
    exportRecords,
    importRecords,
    updateFilters,
    resetFilters,
    toggleRecordSelection,
    toggleSelectAll,
    loadRecords
  }
}) 